import React, { useState, useEffect } from "react";
import { Table, DatePicker, Select, Button, Flex, Input, Tooltip } from "antd";
import "./LogManage.css";
import useCloseLoadingOnMount from "../../../utils/hook/useCloseLoadingOnMount";
import actionLogsApi from "../../../apis/actionLogsApi";

const { RangePicker } = DatePicker;

const LogManage = () => {
  useCloseLoadingOnMount();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [requestMan, setRequestMan] = useState("");
  const [begain, setBegain] = useState(null);
  const [end, setEnd] = useState(null);
  const [flag, setFlag] = useState(false);

  const fetchFunc = async () => {
    setLoading(true);
    try {
      const res = await actionLogsApi.getActionLogsPagination({
        page: pagination.current,
        limit: pagination.pageSize,
        key: requestMan,
        begain: begain ?? "",
        end: end ?? "",
      });
      if (res.status >= 0) {
        setData(res.data.data);
        setPagination({ ...pagination, total: res.data.total });
      }
    } finally {
      setLoading(false);
    }
  };
  // 监听分页对象属性变化，当变化时进行分页
  useEffect(() => {
    fetchFunc();
  }, [pagination.current]);

  useEffect(() => {
    if (flag) {
      if (pagination.current != 1) {
        setPagination({ ...pagination, current: 1 });
      } else {
        fetchFunc();
      }
    }
    setFlag(true);
  }, [pagination.pageSize, pagination.key]);

  const columns = [
    {
      title: "编号",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "消息",
      dataIndex: "message",
      key: "message",
    },
    {
      title: "请求参数(json)",
      dataIndex: "requestParams",
      key: "requestParams",
      render: (text) => {
        const maxLength = 20; // 定义最大显示长度
        if (text.length > maxLength) {
          return (
            <Tooltip
              title={<span style={{ color: "#333" }}>{text}</span>}
              color="#f0f5f9"
            >
              <span
                style={{
                  display: "inline-block",
                  maxWidth: "100%",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  whiteSpace: "nowrap",
                }}
              >
                {text.slice(0, maxLength)}...
              </span>
            </Tooltip>
          );
        }
        return text;
      },
    },
    {
      title: "请求地址",
      dataIndex: "requestUrl",
      key: "requestUrl",
    },
    {
      title: "请求方法",
      dataIndex: "requestMethod",
      key: "requestMethod",
    },
    {
      title: "ip地址",
      dataIndex: "ip",
      key: "ip",
    },
    {
      title: "受影响行数",
      dataIndex: "affectedRows",
      key: "affectedRows",
    },
    {
      title: "请求人",
      dataIndex: "accountId",
      key: "accountId",
    },
    {
      title: "创建时间",
      dataIndex: "createTimeStr",
      key: "createTimeStr",
    },
  ];

  return (
    <div className="body-container1">
      <Flex className="search-bar" align="center">
        <Input
          value={requestMan}
          onChange={(e) => {
            console.log(e.target.value);
          }}
          style={{ width: "200px" }}
          placeholder="请输入操作人"
        ></Input>
        <RangePicker
          showTime
          onChange={(dates) => {
            setBegain(dates.map((d) => d.$d.toLocaleString())[0]);
            setEnd(dates.map((d) => d.$d.toLocaleString())[1]);
          }}
          style={{ width: 320 }}
        />
        <Button
          type="primary"
          onClick={() => {
            if (pagination.current != 1)
              setPagination({ ...pagination, current: 1 });
            else fetchFunc();
          }}
        >
          查询
        </Button>
      </Flex>

      <Table
        className="log-table"
        columns={columns}
        dataSource={data}
        loading={loading}
        rowKey="id"
        scroll={{ x: "max-content" }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          total: pagination.total,
          pageSizeOptions: ["5", "10", "20", "50"],
          onChange: (page, pageSize) => {
            setPagination({ ...pagination, current: page, pageSize });
          },
        }}
      />
    </div>
  );
};

export default LogManage;
